package org.goodsl.mdd.validator;

import groovy.lang.Closure;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
import org.goodsl.mdd.Validator;
import org.goodsl.mdd.SingleValidResult;
import org.goodsl.mdd.Seg;

/**
 * Created with IntelliJ IDEA.
 * User: Simon Xiao
 * Date: 12-11-14
 * Time: 上午11:31
 * To change this template use File | Settings | File Templates.
 */
public class ClosureValidator<T> extends Validator<T>{
    public String name;
    public Closure closure;

    public ClosureValidator(String name,Closure closure,String message){
        super(message);
        this.closure = closure;
        this.name = name;
    }

    @Override
    public SingleValidResult<T> verify(T variable) {
        Closure calc = closure.rehydrate(variable,variable,variable);
        Object value = calc.call();
        if(DefaultTypeTransformation.castToBoolean(value))  //执行groovy风格的true/false判定
            return new SingleValidResult<T>(true, "", variable, this);
        else
            return new SingleValidResult<T>(false, getMessage(), variable, this);
    }
}
